package org.example.classtopia.Controller;

import org.example.classtopia.Common.Result.Result;
import org.example.classtopia.Model.dto.CourseCreateDTO;
import org.example.classtopia.Model.dto.CourseUpdateDTO;
import org.example.classtopia.Model.dto.CourseQueryDTO;
import org.example.classtopia.Model.vo.CourseVO;
import org.example.classtopia.Model.vo.PageResultVO;
import org.example.classtopia.Model.Entity.Course;
import org.example.classtopia.Service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalTime;
import java.util.List;

/**
 * 课程管理接口
 *
 * 提供课程创建、查询、修改、删除、分页查询一周课程功能。
 *
 * - 创建课程：POST /courses
 * - 查询单个课程：GET /courses/{id}
 * - 按用户、学期、周次分页查询课程：GET /courses/week
 * - 修改课程：PUT /courses
 * - 删除课程：DELETE /courses/{id}
 *
 * 所有接口均返回统一响应结构，包含 code、message、data 字段。
 */
@RestController
@RequestMapping("/courses")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 创建课程
     */
    private boolean isValidTimeFormat(String timeStr) {
        try {
            LocalTime.parse(timeStr);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @PostMapping
    public Result<CourseVO> createCourse(@RequestBody CourseCreateDTO courseCreateDTO) {
        if (courseCreateDTO.getUserId() == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if (!StringUtils.hasText(courseCreateDTO.getEventType()) ||
                (!"course".equals(courseCreateDTO.getEventType()) && !"schedule".equals(courseCreateDTO.getEventType()))) {
            return Result.error(400, "事件类型必须是 course 或 schedule");
        }
        if (!StringUtils.hasText(courseCreateDTO.getName())) {
            return Result.error(400, "课程名称不能为空");
        }
        if (courseCreateDTO.getDayOfWeek() == null || courseCreateDTO.getDayOfWeek() < 1 || courseCreateDTO.getDayOfWeek() > 7) {
            return Result.error(400, "星期几(dayOfWeek)必须在1到7之间");
        }
        if (courseCreateDTO.getStartTime() == null || courseCreateDTO.getEndTime() == null) {
            return Result.error(400, "开始时间和结束时间不能为空");
        }
        if (courseCreateDTO.getStartWeek() == null || courseCreateDTO.getEndWeek() == null || courseCreateDTO.getStartWeek() > courseCreateDTO.getEndWeek()) {
            return Result.error(400, "周次范围不正确");
        }
        if (!StringUtils.hasText(courseCreateDTO.getSemester())) {
            return Result.error(400, "学期不能为空");
        }
        // 时间格式校验
        if (!isValidTimeFormat(courseCreateDTO.getStartTime()) || !isValidTimeFormat(courseCreateDTO.getEndTime())) {
            return Result.error(400, "开始时间或结束时间格式错误，必须为HH:mm");
        }

        // 事件特有校验
        if ("course".equals(courseCreateDTO.getEventType())) {
            if (!StringUtils.hasText(courseCreateDTO.getTeacher())) {
                return Result.error(400, "课程事件必须填写教师姓名");
            }
            if (courseCreateDTO.getDescription() != null && !courseCreateDTO.getDescription().trim().isEmpty()) {
                return Result.error(400, "课程事件不允许填写描述");
            }
        } else {
            if (!StringUtils.hasText(courseCreateDTO.getDescription())) {
                return Result.error(400, "日程事件必须填写描述");
            }
            if (courseCreateDTO.getTeacher() != null && !courseCreateDTO.getTeacher().trim().isEmpty()) {
                return Result.error(400, "日程事件不允许填写教师姓名");
            }
        }

        try {
            Course course = courseService.createCourse(courseCreateDTO);
            if (course == null) {
                return Result.error(500, "课程创建失败，可能存在时间冲突");
            }
            CourseVO vo = courseService.getCourseById(course.getId());
            //return Result.success("创建成功", savedCourse);

            return Result.success("创建成功", vo);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询课程详情
     */
    @GetMapping("/{id}")
    public Result<CourseVO> getCourseById(@PathVariable Long id) {
        try {
            CourseVO vo = courseService.getCourseById(id);
            if (vo == null) {
                return Result.error(404, "课程不存在");
            }
            return Result.success("查询成功", vo);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    /**
     * 按用户ID、学期和周次分页查询该周课程
     */
    @GetMapping("/week")
    public Result<List<CourseVO>> getCoursesByUserAndWeek(
            @RequestParam Long userId,
            @RequestParam String semester,
            @RequestParam Integer week) {

        if (userId == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if (!StringUtils.hasText(semester)) {
            return Result.error(400, "学期不能为空");
        }
        if (week == null || week < 1) {
            return Result.error(400, "周次必须大于0");
        }

        try {
            CourseQueryDTO queryDTO = new CourseQueryDTO();
            queryDTO.setUserId(userId);
            queryDTO.setSemester(semester);
            queryDTO.setWeek(week);

            List<CourseVO> courses = courseService.getCoursesByUserAndWeek(queryDTO);
            return Result.success("查询成功", courses);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }


    /**
     * 修改课程
     */
    @PutMapping
    public Result<Boolean> updateCourse(@RequestBody CourseUpdateDTO courseUpdateDTO) {
        if (courseUpdateDTO.getId() == null) {
            return Result.error(400, "课程ID不能为空");
        }

        if (courseUpdateDTO.getStartTime() != null && !isValidTimeFormat(courseUpdateDTO.getStartTime())) {
            return Result.error(400, "开始时间格式错误，必须为HH:mm");
        }

        if (courseUpdateDTO.getEndTime() != null && !isValidTimeFormat(courseUpdateDTO.getEndTime())) {
            return Result.error(400, "结束时间格式错误，必须为HH:mm");
        }

        // 事件特有校验
        if ("course".equals(courseUpdateDTO.getEventType())) {
            if (!StringUtils.hasText(courseUpdateDTO.getTeacher())) {
                return Result.error(400, "课程事件必须填写教师姓名");
            }
            if (courseUpdateDTO.getDescription() != null && !courseUpdateDTO.getDescription().trim().isEmpty()) {
                return Result.error(400, "课程事件不允许填写描述");
            }
        } else {
            if (!StringUtils.hasText(courseUpdateDTO.getDescription())) {
                return Result.error(400, "日程事件必须填写描述");
            }
            if (courseUpdateDTO.getTeacher() != null && !courseUpdateDTO.getTeacher().trim().isEmpty()) {
                return Result.error(400, "日程事件不允许填写教师姓名");
            }
        }

        try {
            boolean updated = courseService.updateCourse(courseUpdateDTO);
            if (!updated) {
                return Result.error(500, "更新失败，可能存在时间冲突或者课程不存在");
            }
            return Result.success("更新成功", true);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }

    /**
     * 删除课程（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCourse(@PathVariable Long id) {
        try {
            boolean deleted = courseService.deleteCourseById(id);
            if (!deleted) {
                return Result.error(500, "删除失败");
            }
            return Result.success("删除成功", true);
        } catch (Exception e) {
            return Result.error("服务器内部错误：" + e.getMessage());
        }
    }
}

